import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth'
import Constants from "@/Constants";
import RouterUtil from "@/router/RouterUtil"; // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect' ,'404', '401' ] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  to.query.timestamp = Date.now() ;
  const hasToken = getToken()
  saveMenuPath(to)
  if (hasToken) {// 已登录
    if (to.path === '/login') {
      next({ path: '/' })
    } else if(to.path.startsWith("/admin")) {
      if(RouterUtil.isLoadAdminMenu()){
        store.dispatch("GetMenu").then(menus=>{
          RouterUtil.addRoutes(menus)
          next()
        })
      }else{
        next()
      }

    }else{
      next()
    }
  } else {//未登录
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
    }
  }

})

router.afterEach(() => {
  NProgress.done()
})


function saveMenuPath(to){
  store.commit(Constants.setMenuActive,to.path)
}
